import React from 'react'
import './waterfall.css'

function Waterfall(props) {
    let refs = [];
    const data = props.data;
    const col = props.col
    const [vdata, setVdata] = React.useState([]);
    for (let i = 0; i < col; i++) {
        refs[i] = React.createRef();
    }
    React.useEffect(()=>{
        let ar = []
        for (let i = 0; i < col; i++) {
            ar[i] = []
        }
        setVdata(ar)
    },[])
    React.useEffect(() => {
        let heights = [];

            setTimeout(()=>{
                try {
                for (let i = 0; i < col; i++) {
                    let dom = refs[i];
                    heights[i] = dom.current.offsetHeight
                }
                if (data.length > 0) {
                    let min = 0;
                    for (let i = 0; i < heights.length; i++) {
                        if (heights[i] < heights[min]) {
                            min = i
                        }
                    }
                    vdata[min].push(data.shift())
                    console.log('ok')
                    setVdata([...vdata]);
                }
                } catch (e) {
                    console.log(e)
                }
            },100)


    }, [vdata])

    function setpadding(index) {
        let gap = props.gap;
        if(index!=col-1&&index!=0){
            return `0 ${gap/2+"px"} 0 ${gap/2+"px"}`
        }
        if(index!=col-1){
            return `0 ${gap/2+"px"} 0 0`
        }
        if(index!=0){
            return `0 0 0 ${gap/2+"px"}`
        }
    }

    return (
        <div className={'waterfall'}>
            {vdata.map((val, index) => {
                return (
                    <div className={'w_item'} style={{width: 100 / col + '%',padding:setpadding(index)}} key={index}>
                        <div ref={refs[index]}>
                            {vdata[index].map((item,k)=>{
                                return  <div key={k}>{
                                    props.temp(item)
                                }</div>
                            })}

                        </div>
                    </div>
                )
            })}

        </div>
    )
}

export default Waterfall